package com.oceansoft.mobile.weixin.util;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;


/**
 * Controll层公用方法
 * 
 * @author Administrator
 * 
 */
public class RequestUtils {

	final private static int maxsizefj = 500000;
	
	/**
	 * 将request中的对象映射到map
	 * 
	 */
	public static Map<String, String> buildParamsByNamesFromRequest(
			HttpServletRequest request) {
		Map<?, ?> mp = request.getParameterMap(); // 获取客户端传递过来的所有参数
		@SuppressWarnings("unchecked")
		Set<String> keySet = (Set<String>) mp.keySet();
		HashMap<String, String> result = new HashMap<String, String>();
		for (String name : keySet) {
			String paramName = name;
			String paramValue = null;
			if (name.indexOf("|") > 0) {
				String[] nameValue = name.split("[|]");
				paramName = nameValue[0];
				paramValue = nameValue[1];
			}
			String nameObject = request.getParameter(paramName);
				if (StringUtils.hasText(nameObject)) {
					result.put(paramName, nameObject.trim());
				} else {
					if (paramValue != null)
						result.put(paramName, paramValue.trim());
				}

		}
		return result;
	}

	public static  JSONObject map2Json(Map<String, String> m)
	{
		JSONObject json = new JSONObject();
		Set<String> keySet  = m.keySet();
		for (String k : keySet) {
			json.put(k, m.get(k));
		}
		return json;
	}
	
	public static JSONObject buildParamsByNamesFromRequest4JSON(
			HttpServletRequest request) {
		Map<?, ?> mp = request.getParameterMap(); // 获取客户端传递过来的所有参数
		JSONObject json = new JSONObject();
		@SuppressWarnings("unchecked")
		Set<String> keySet = (Set<String>) mp.keySet();
		for (String name : keySet) {
			String paramName = name;
			String paramValue = null;
			if (name.indexOf("|") > 0) {
				String[] nameValue = name.split("[|]");
				paramName = nameValue[0];
				paramValue = nameValue[1];
			}
			String nameObject = request.getParameter(paramName);
				if (StringUtils.hasText(nameObject)) {
					json.put(paramName, nameObject.trim());
				} else {
					if (paramValue != null)
						json.put(paramName, paramValue.trim());
				}

		}
		return json;
	}
	
	/**
	 * 保存附件到大厅 仅限图片
	 * @param request
	 * @param fileField
	 * @param caseMatGuid
	 * @param isbase64
	 * @return
	 */
	public static Result saveFj(HttpServletRequest request,String fileField,String caseMatGuid,boolean isbase64)
	{
		JSONObject param = new JSONObject();
//		Map param = new HashMap();
		if(isbase64)
		{
			byte[] content = Base64.decodeBase64(fileField.getBytes());
			if(caseMatGuid.length()>=8)
			{
				param.put("fileName", caseMatGuid.substring(8)+new Date().getTime()+".png");
			}
			else
			{
				param.put("fileName",new Date().getTime()+".png");
			}
			param.put("fileExtension", ".png");
			param.put("fileData", fileField);
			param.put("fileSize", content.length+"");
		}
		else
		{
			CommonsMultipartFile file = (CommonsMultipartFile) ((MultipartHttpServletRequest)request).getFile(fileField)   ;
			byte[] output =  file.getBytes();
			if(output.length>maxsizefj)
			{
				float quality = (float)((float)maxsizefj/(float)output.length);
				output = compressPic(output,quality);
			}
			BASE64Encoder encoder = new BASE64Encoder();
		    String outstr =  encoder.encode(output);
		    String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1,file.getOriginalFilename().length());
		    param.put("fileName", file.getOriginalFilename());
			param.put("fileExtension", "."+fileType);
			param.put("fileSize", output.length+"");
			param.put("fileData", outstr);
		}
		param.put("caseMatGuid",caseMatGuid);
		Result result = new  Result();
		try {
			result = HttpClientUtil.doGAUrlPost(Constant.host5+("api/Product/SaveProjectMat"), param);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSucc(false);
			result.setMsg(e.getMessage());
		}
		System.out.println(JSONObject.toJSON(result));
		return result;
	}
	
	
	
	/**
	 * 上传特殊事项数据  
	 * @param request
	 * @param url
	 * @return
	 */
	public static Result saveSpecific(JSONObject param,String url ){
		if(StringUtils.hasText(url)&&url.toLowerCase().startsWith("http"))
		{
			
		}
		else
		{
			url = Constant.host5 + url;
		}
		
		Result result = new Result();
		try {
			result = HttpClientUtil.doGAUrlPost(url, param);
		} catch (IOException e) {
			result.setSucc(false);
			result.setMsg(e.getMessage());
			e.printStackTrace();
		}
		System.out.println(JSONObject.toJSON(result));
		return result;
	}
	
	/***
	 * 申报接口 公共方法
	 * @param request
	 * @param specific 特殊事项对应的session attribute result返回的guid
	 * @param fjname   附件对应的session Attribute  上传的附件返回的result 
	 * @param islogin  是否需要加载用户信息
	 * @return
	 */
	public static Result submitShenbao(JSONObject param,HttpServletRequest request,String specific,String fjname,boolean islogin){
		String url = Constant.host5 +"api/Product/Shenbao";
		//讲request中的参数合并到param中
		JSONObject requestparam = buildParamsByNamesFromRequest4JSON(request);
		Set<String> k = requestparam.keySet();
		for (String s : k) {
			param.put(s, requestparam.get(s));
		}
		if(StringUtils.hasText(specific))
		{
			param.put("projectGuid", specific);
		}
		if(StringUtils.hasText(fjname))
		{
			//获取附件id
			Map<String ,Result> m = (Map<String ,Result>)request.getSession().getAttribute(fjname);
			request.getSession().removeAttribute(fjname);
			JSONArray fjlist = new JSONArray();
			//循环读取附件
			if(m!=null&&!m.isEmpty())
			{
				Set<String> fjkeys = m.keySet();
				for (String key : fjkeys) {
					Result r = m.get(key);
					JSONObject fjjson = new JSONObject();
					fjjson.put("id",((JSONObject)r.getData()).get("prjMatGuid"));
					fjjson.put("caseMatID", ((JSONObject)r.getData()).get("caseMatGuid"));
					fjlist.add(fjjson);
				}
				param.put("matLifo_att", fjlist.toJSONString());
				System.out.println("关联附件信息:"+fjlist.toJSONString());
			}
		}
		//附加用户信息
		if(islogin)
		{
			putUser4json(request, param);
		}
		Result result = new Result();
		try {
			result = HttpClientUtil.doGAUrlPost(url, param);
		} catch (IOException e) {
			result.setSucc(false);
			result.setMsg(e.getMessage());
			e.printStackTrace();
		}
		System.out.println(JSONObject.toJSON(result));
		HttpSession session=request.getSession();
		session.setAttribute("ywid",result.getData());
		return result;
	}
	
	
	public static Result submitShenbao4request(HttpServletRequest request,String specific,String fjname,boolean islogin){
		String url = Constant.host5 +"api/Product/Shenbao";
		JSONObject param = buildParamsByNamesFromRequest4JSON(request);
		if(StringUtils.hasText(specific))
		{
			param.put("projectGuid", specific);
		}
		
		if(StringUtils.hasText(fjname))
		{
			//获取附件id
			Map<String ,Result> m = (Map<String ,Result>)request.getSession().getAttribute(fjname);
			request.getSession().removeAttribute(fjname);
			JSONArray fjlist = new JSONArray();
			//循环读取附件
			if(m!=null&&!m.isEmpty())
			{
				Set<String> fjkeys = m.keySet();
				for (String key : fjkeys) {
					Result r = m.get(key);
					JSONObject fjjson = new JSONObject();
					fjjson.put("id",((JSONObject)r.getData()).get("prjMatGuid"));
					fjjson.put("caseMatID", ((JSONObject)r.getData()).get("caseMatGuid"));
					fjlist.add(fjjson);
				}
				param.put("matLifo_att", fjlist.toJSONString());
				System.out.println("关联附件信息:"+fjlist.toJSONString());
			}
		}
		//附加用户信息
		if(islogin)
		{
			putUser4json(request, param);
		}
		Result result = new Result();
		try {
			result = HttpClientUtil.doGAUrlPost(url, param);
		} catch (IOException e) {
			result.setSucc(false);
			result.setMsg(e.getMessage());
			e.printStackTrace();
		}
		System.out.println(JSONObject.toJSON(result));
		HttpSession session=request.getSession();
		session.setAttribute("ywid",result.getData());
		return result;
	}
	
	
	
	public static void putUser4json(HttpServletRequest request, JSONObject param) {
		 Member user = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
	        if(null!=user)
	        {
	        	System.out.println("提交的用户信息:" + JSONObject.toJSONString(user));
	        	if(StringUtils.isEmpty(param.get("declareUserGuid")))
	            {
	        		 param.put("declareUserGuid", user.getGuid());
	            }
	            if(StringUtils.isEmpty(param.get("createUserId")))
	            {
	            	 param.put("createUserId", param.get("declareUserGuid"));
	            }
	            if(StringUtils.isEmpty(param.get("userType")))
	            {
	            	 param.put("userType", user.getType()+"");
	            }
	            if(StringUtils.isEmpty(param.get("AliasName")))
	            {
	            	param.put("AliasName", user.getRealName());
	            }
	            if(StringUtils.isEmpty(param.get("UserCode")))
	            {
	            	param.put("UserCode", user.getType()==1?user.getIdCard():user.getOrgId());
	            }
	            if(StringUtils.isEmpty(param.get("Address")))
	            {
	            	 param.put("Address", user.getAddress());
	            }
	            if(StringUtils.isEmpty(param.get("TelePhone")))
	            {
	            	  param.put("TelePhone", user.getTel());
	            }
	            if(StringUtils.isEmpty(param.get("LinkName")))
	            {
	            	param.put("LinkName", user.getContacts());
	            }
	            if(StringUtils.isEmpty(param.get("Mobile")))
	            {
	            	param.put("Mobile", user.getMobile());
	            }
	        }
	        //开发数据全部放在00000用户
	        //param.put("declareUserGuid", "00000");
	        
//	        if(StringUtils.isEmpty(param.get("declareUserGuid")))
//	        {
//	        	 param.put("declareUserGuid", "00000");
//	        }
	        if(StringUtils.isEmpty(param.get("createUserId")))
	        {
	        	 param.put("createUserId", param.get("declareUserGuid"));
	        }
	        if(StringUtils.isEmpty(param.get("userType")))
	        {
	        	 param.put("userType", "1");
	        }
	        if(StringUtils.isEmpty(param.get("AliasName")))
	        {
	        	 param.put("AliasName", "测试用户");
	        }
	        if(StringUtils.isEmpty(param.get("UserCode")))
	        {
	        	 param.put("UserCode", "888888");
	        }
	        if(StringUtils.isEmpty(param.get("Address")))
	        {
	        	 param.put("Address", "测试地址");
	        }
	        if(StringUtils.isEmpty(param.get("TelePhone")))
	        {
	        	 param.put("TelePhone", "11111111");
	        }
	        if(StringUtils.isEmpty(param.get("LinkName")))
	        {
	        	 param.put("LinkName", "测试联系人");
	        }
	        if(StringUtils.isEmpty(param.get("Mobile")))
	        {
	        	 param.put("Mobile", "13888888888");
	        }
	 }
	
	 /**
     * 将用户信息放到参数中
     * @param request
     * @param param
     */
    public static void putUser(HttpServletRequest request, Map<String, String> param) {
    	Member user = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
        if(null!=user)
        {
        	System.out.println("提交的用户信息:" + JSONObject.toJSONString(user));
        	if(StringUtils.isEmpty(param.get("declareUserGuid")))
            {
        		 param.put("declareUserGuid", user.getGuid());
            }
            if(StringUtils.isEmpty(param.get("createUserId")))
            {
            	 param.put("createUserId", param.get("declareUserGuid"));
            }
            if(StringUtils.isEmpty(param.get("userType")))
            {
            	 param.put("userType", user.getType()+"");
            }
            if(StringUtils.isEmpty(param.get("AliasName")))
            {
            	param.put("AliasName", user.getRealName());
            }
            if(StringUtils.isEmpty(param.get("UserCode")))
            {
            	param.put("UserCode", user.getType()==1?user.getIdCard():user.getOrgId());
            }
            if(StringUtils.isEmpty(param.get("Address")))
            {
            	 param.put("Address", user.getAddress());
            }
            if(StringUtils.isEmpty(param.get("TelePhone")))
            {
            	  param.put("TelePhone", user.getTel());
            }
            if(StringUtils.isEmpty(param.get("LinkName")))
            {
            	param.put("LinkName", user.getContacts());
            }
            if(StringUtils.isEmpty(param.get("Mobile")))
            {
            	param.put("Mobile", user.getMobile());
            }
        }
        //开发数据全部放在00000用户
        //param.put("declareUserGuid", "00000");
        
//        if(StringUtils.isEmpty(param.get("declareUserGuid")))
//        {
//        	 param.put("declareUserGuid", "00000");
//        }
        if(StringUtils.isEmpty(param.get("createUserId")))
        {
        	 param.put("createUserId", param.get("declareUserGuid"));
        }
        if(StringUtils.isEmpty(param.get("userType")))
        {
        	 param.put("userType", "1");
        }
        if(StringUtils.isEmpty(param.get("AliasName")))
        {
        	 param.put("AliasName", "测试用户");
        }
        if(StringUtils.isEmpty(param.get("UserCode")))
        {
        	 param.put("UserCode", "888888");
        }
        if(StringUtils.isEmpty(param.get("Address")))
        {
        	 param.put("Address", "测试地址");
        }
        if(StringUtils.isEmpty(param.get("TelePhone")))
        {
        	 param.put("TelePhone", "11111111");
        }
        if(StringUtils.isEmpty(param.get("LinkName")))
        {
        	 param.put("LinkName", "测试联系人");
        }
        if(StringUtils.isEmpty(param.get("Mobile")))
        {
        	 param.put("Mobile", "13888888888");
        }
    }
    
    
 // 压缩图片的方法
 	public static byte[] compressPic(byte[] pic, float quality) {

 		ByteArrayInputStream is = new ByteArrayInputStream(pic);

 		BufferedImage src = null;
 		ByteArrayOutputStream out = null;
 		ImageWriter imgWrier;
 		ImageWriteParam imgWriteParams;

 		// 指定写图片的方式为 jpg
 		imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
 		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
 		// 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
 		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
 		// 这里指定压缩的程度，参数qality是取值0~1范围内，
 		imgWriteParams.setCompressionQuality(quality);

 		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
 		ColorModel colorModel = ColorModel.getRGBdefault();
 		// 指定压缩时使用的色彩模式
 		imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));

 		try {
 			src = ImageIO.read(is);
 			out = new ByteArrayOutputStream(pic.length);

 			imgWrier.reset();
 			// 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
 			imgWrier.setOutput(ImageIO.createImageOutputStream(out));
 			// 调用write方法，就可以向输入流写图片
 			imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);

 			out.flush();
 			out.close();
 			is.close();
 			return out.toByteArray();
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 		return null;
 	}
	
}
